﻿Public Class frmAgregarItemEspecial


    Dim idagrupa As Integer = 1

    Public Sub AgregarProductoDesdeBotonPersonalizado(ByVal textbox As System.Windows.Forms.TextBox)
        Try
            gdItemVenta.EditValue = CInt(textbox.Text)
            btAgregar.PerformClick()
        Catch ex As Exception
            LogSGS.RegistrarLogSinEnviarCorreo(My.Resources.StringGlobal.prgVinicio, "Error al momento de agregar un producto desde los botones personalizados en la pantalla de facturación", ex, My.Resources.StringGlobal.mdlFacturacion, Name, "AgregarProductoDesdeBotonPersonalizado")
        End Try
    End Sub

    Public Sub ConstruirBotones()
        Try
            BotonesPersonalizadosSGS.ConstruirMenuRapidoPlatoDinamico(txt10, btn10, txt11, btn11, txt12, btn12, txt13, btn13, txt14, btn14, txt15, btn15, txt16, btn16, txt17, btn17, txt18, btn18)
        Catch ex As Exception
            LogSGS.RegistrarLogSinEnviarCorreo(My.Resources.StringGlobal.prgVinicio, "Error al momento de construir los botones personalizados en la pantalla de facturación", ex, My.Resources.StringGlobal.mdlFacturacion, Name, "ConstruirBotones")
        End Try
    End Sub

    Private Sub frmAgregarItemEspecial_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        ConstruirBotones()
        'Me.ItemespecialdetalleTableAdapter.Fill(Me.DbFireAndIceDataSet.itemespecialdetalle)
        ItemventaTableAdapter.FillByTipoProducto(Me.DbFireAndIceDataSet.itemventa, 7, 8)

        ErrorProvider1.SetError(gdItemVenta, Nothing)
        ErrorProvider1.SetError(tCantidad, Nothing)

        tItem.EditValue = My.Forms.frmFactura.IditemventaTextEdit.EditValue
        tCantidad.EditValue = 1
        Dim row As DataRowView = CType(My.Forms.frmFactura.IditemventaTextEdit.Properties.GetRowByKeyValue(My.Forms.frmFactura.IditemventaTextEdit.EditValue), DataRowView)
        Dim precio As Object = row("precioventa")
        tPrecio.EditValue = precio
        gdItemVenta.Focus()

        If ItemespecialdetalleTableAdapter.ScalarQueryObtieneUltimoIdagrupa() Then
            idagrupa = ItemespecialdetalleTableAdapter.ScalarQueryObtieneUltimoIdagrupa() + 1
        End If
        ItemespecialdetalleTableAdapter.FillByIdagrupa(DbFireAndIceDataSet.itemespecialdetalle, idagrupa)
    End Sub

    Private Sub btAgregar_Click(sender As System.Object, e As System.EventArgs) Handles btAgregar.Click
        If gdItemVenta.Text.Length = 0 Then
            ErrorProvider1.SetError(gdItemVenta, "Debe ingresar un Item de Venta")
        ElseIf tCantidad.EditValue <= 0 Then
            ErrorProvider1.SetError(tCantidad, "Debe ingresar una cantidad")
        Else
            ErrorProvider1.SetError(gdItemVenta, Nothing)
            ErrorProvider1.SetError(tCantidad, Nothing)

            Dim row As DataRowView = CType(gdItemVenta.Properties.GetRowByKeyValue(gdItemVenta.EditValue), DataRowView)
            Dim tipo As Object = row("idtipo")

            Dim agrega As Boolean = True
            Dim total_items As Integer = 0 'total complementos
            If tipo = 8 Then
                If ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 8) Then
                    total_items = ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 8)
                End If
                If total_items > 0 Then
                    agrega = False
                End If
            Else
                If ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 7) Then
                    total_items = ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 7)
                End If
                If total_items > 2 Then
                    agrega = False
                End If
            End If

            If agrega Then
                Try
                    Dim connectionstring As String = GetConnnectionString()
                    Dim conn As New Devart.Data.PostgreSql.PgSqlConnection(connectionstring)
                    conn.Open()
                    Dim query As String = "select reduce_existencia_x_item(" + Str(gdItemVenta.EditValue) + "," + Str(tCantidad.EditValue) + ");"
                    Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(query, conn)
                    comando.ExecuteNonQuery()

                    Dim correlativo As Integer = 1

                    If ItemespecialdetalleTableAdapter.ScalarQueryObtieneUltCorrelativo() Then
                        correlativo = ItemespecialdetalleTableAdapter.ScalarQueryObtieneUltCorrelativo() + 1
                    End If

                    Dim row1 As DataRowView = CType(gdItemVenta.Properties.GetRowByKeyValue(gdItemVenta.EditValue), DataRowView)
                    Dim tipo1 As Object = row("idtipo")

                    ConexionSGS.EjecutarQueryNonQuery(String.Format("INSERT INTO itemespecialdetalle(idcorrelativo, idfactura, iditemventa, cantidad, idagrupaitem, idtipo) VALUES ({0}, (SELECT COALESCE(MAX(idfactura),1) AS EXPR1 FROM facturas GROUP BY nombrepc HAVING (nombrepc = '{1}')), {2}, {3}, {4}, {5});", correlativo, My.Computer.Name, gdItemVenta.EditValue, tCantidad.EditValue, idagrupa, tipo1))
                    'ItemespecialdetalleTableAdapter.InsertQuery(correlativo, My.Forms.frmFactura.IdfacturaTextBox.Text, _
                    '                                            gdItemVenta.EditValue, tCantidad.EditValue, idagrupa, _
                    '                                           tipo1)

                    ItemespecialdetalleTableAdapter.FillByIdagrupa(DbFireAndIceDataSet.itemespecialdetalle, idagrupa)
                    gdItemVenta.EditValue = Nothing
                    gdItemVenta.Focus()
                    tCantidad.EditValue = 1
                Catch ex As Exception
                    AlertControl1.AppearanceCaption.ForeColor = Color.Red
                    AlertControl1.Show(Me, "Error", "No se agregó el producto a la venta.")
                    TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                                                      My.Resources.StringGlobal.prgAngely, _
                                                      "Error en el botón agregar en frmAgregarItemEspecial.", _
                                                      ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, _
                                                      TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
                End Try
            Else
                MsgBox("Ya agregó el limite de este producto", MsgBoxStyle.Exclamation, "Notificación")
            End If
           
        End If
    End Sub

    Public Function GetConnnectionString()
        Const fic As String = "configuracion.txt"
        Dim diract As String = ""
        diract = System.IO.Directory.GetCurrentDirectory()

        Dim direccion As String = ""

        direccion = String.Format("{0}\{1}", diract, fic)

        Dim connstring As String = ""
        Try
            Dim sr As New System.IO.StreamReader(direccion)
            connstring = sr.ReadToEnd()
            sr.Close()
            Console.WriteLine(connstring)
        Catch ex As Exception
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "Error al obtener la conexion con la base de datos.")
            TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                                              My.Resources.StringGlobal.prgAngely, _
                                              "Error en la función GetConnnectionString de la pantalla frmAgregarItemEspecial.", _
                                              ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, _
                                              TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, "GetConnnectionString")
        End Try
        Return connstring
    End Function

    Private Sub btTerminar_Click(sender As System.Object, e As System.EventArgs) Handles btTerminar.Click
        Try
            Dim agrega As Boolean = False
            Dim total_items As Integer = 0 'total complementos

            If ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 8) Then
                total_items = ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 8)
            End If
            If total_items = 1 Then
                If ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 7) Then
                    total_items = ItemespecialdetalleTableAdapter.ScalarQueryObtieneTotalItemsPorTipo(idagrupa, 7)
                End If
                If total_items = 3 Then
                    agrega = True
                End If
            End If

            If agrega Then
                Dim connectionstring As String = GetConnnectionString()
                Dim conn As New Devart.Data.PostgreSql.PgSqlConnection(connectionstring)
                conn.Open()

                Dim row As DataRowView = CType(My.Forms.frmFactura.IditemventaTextEdit.Properties.GetRowByKeyValue(My.Forms.frmFactura.IditemventaTextEdit.EditValue), DataRowView)
                Dim costo As Object = row("costototal")

                Dim query2 As String = "select inserta_factdet_temp(" + Str(My.Forms.frmFactura.IditemventaTextEdit.EditValue) + _
                            ", " + Str(My.Forms.frmFactura.tcantidad.Value) + "," + Str(My.Forms.frmFactura.ttotallinea.EditValue) + _
                            ", " + Str(My.Forms.frmFactura.tprecioventa.EditValue) + "," + Str(costo) + ",(SELECT COALESCE(MAX(idfactura),1) AS idfact FROM facturas where nombrepc = 'ANGELYDIAZ-PC'))"
                Dim comando2 As New Devart.Data.PostgreSql.PgSqlCommand(query2, conn)
                comando2.ExecuteNonQuery()

                Dim consumodia As Integer
                consumodia = Val(FacturasTableAdapter1.ScalarQuerySubsidioConsumido(My.Forms.frmFactura.FechaDateTimePicker.Text, My.Forms.frmFactura.IdclienteTextEdit.EditValue))
                If IsDBNull(consumodia) Then
                    consumodia = 0
                End If

                If EmpresaitemsubsidiadoTableAdapter1.ScalarQueryDevuelveIdItem(My.Forms.frmFactura.IditemventaTextEdit.EditValue) Then
                    If EmpresaitemsubsidiadoTableAdapter1.ScalarQueryDevuelveIdItem(My.Forms.frmFactura.IditemventaTextEdit.EditValue) > 0 Then
                        My.Forms.frmFactura.subsidiodisp.EditValue = My.Forms.frmFactura.subsidiootorgado.EditValue - consumodia
                    End If
                End If

                Close()
            Else
                ErrorProvider1.SetError(gdItemVenta, "Debe ingresar un Item de Venta")
            End If
        Catch ex As Exception
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "Ha ocurrido un error al intentar terminar el proceso.")
            TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                                              My.Resources.StringGlobal.prgAngely, _
                                              "Error en el botón Terminar de la pantalla frmAgregarItemEspecial.", _
                                              ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, _
                                              TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
        End Try
    End Sub

    Private Sub gdItemVenta_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles gdItemVenta.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            btAgregar.PerformClick()
        End If
    End Sub

    Private Sub btCancelar_Click(sender As System.Object, e As System.EventArgs) Handles btCancelar.Click
        Try
            'regresar existencia de productos
            Dim connectionstring As String = GetConnnectionString()
            Dim conn As New Devart.Data.PostgreSql.PgSqlConnection(connectionstring)
            conn.Open()
            Dim query As String = "SELECT aumenta_existencias_itemespecial_agrupado(" + Str(idagrupa) + ");"
            Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(query, conn)
            comando.ExecuteNonQuery()

            ItemespecialdetalleTableAdapter.DeleteQueryPorIdAgrupa(idagrupa)
            Close()
        Catch ex As Exception
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "Error al obtener la conexion con la base de datos.")
            TlogTableAdapter1.InsertQueryLogs(TlogTableAdapter1.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, _
                                              My.Resources.StringGlobal.prgAngely, _
                                              "Error en la función GetConnnectionString de la pantalla frmAgregarItemEspecial.", _
                                              ex.Message, My.Resources.StringGlobal.mdlFacturacion, Date.Today, _
                                              TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, "GetConnnectionString")
        End Try
        
    End Sub

    Private Sub btEliminar_Click(sender As System.Object, e As System.EventArgs) Handles btEliminar.Click
        If gdItemVenta.Text.Length = 0 Then
            ErrorProvider1.SetError(gdItemVenta, "Debe ingresar un Item de Venta")
        ElseIf tCantidad.EditValue <= 0 Then
            ErrorProvider1.SetError(tCantidad, "Debe ingresar una cantidad")
        Else
            ErrorProvider1.SetError(gdItemVenta, Nothing)
            ErrorProvider1.SetError(tCantidad, Nothing)

            'regresar existencia de productos
            Dim connectionstring As String = GetConnnectionString()
            Dim item As Integer = GridView1.GetRowCellValue(GridView1.FocusedRowHandle, "iditemventa")
            Dim conn As New Devart.Data.PostgreSql.PgSqlConnection(connectionstring)
            conn.Open()
            Dim query As String = "select aumenta_existencia_x_item(" + Str(item) + ", 1);"
            Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(query, conn)
            comando.ExecuteNonQuery()

            ItemespecialdetalleTableAdapter.DeleteQuery(GridView1.GetRowCellValue(GridView1.FocusedRowHandle, "idcorrelativo"))
            ItemespecialdetalleTableAdapter.FillByIdagrupa(DbFireAndIceDataSet.itemespecialdetalle, idagrupa)
        End If
    End Sub

   
    Private Sub btn10_Click(sender As System.Object, e As System.EventArgs) Handles btn10.Click
        AgregarProductoDesdeBotonPersonalizado(txt10)
    End Sub

    Private Sub btn11_Click(sender As System.Object, e As System.EventArgs) Handles btn11.Click
        AgregarProductoDesdeBotonPersonalizado(txt11)
    End Sub

    Private Sub btn12_Click(sender As System.Object, e As System.EventArgs) Handles btn12.Click
        AgregarProductoDesdeBotonPersonalizado(txt12)
    End Sub

    Private Sub btn13_Click(sender As System.Object, e As System.EventArgs) Handles btn13.Click
        AgregarProductoDesdeBotonPersonalizado(txt13)
    End Sub

    Private Sub btn14_Click(sender As System.Object, e As System.EventArgs) Handles btn14.Click
        AgregarProductoDesdeBotonPersonalizado(txt14)
    End Sub

    Private Sub btn15_Click(sender As System.Object, e As System.EventArgs) Handles btn15.Click
        AgregarProductoDesdeBotonPersonalizado(txt15)
    End Sub

    Private Sub btn16_Click(sender As System.Object, e As System.EventArgs) Handles btn16.Click
        AgregarProductoDesdeBotonPersonalizado(txt16)
    End Sub

    Private Sub btn17_Click(sender As System.Object, e As System.EventArgs) Handles btn17.Click
        AgregarProductoDesdeBotonPersonalizado(txt17)
    End Sub

    Private Sub btn18_Click(sender As System.Object, e As System.EventArgs) Handles btn18.Click
        AgregarProductoDesdeBotonPersonalizado(txt18)
    End Sub

    Private Sub SimpleButton8_Click(sender As System.Object, e As System.EventArgs) Handles SimpleButton8.Click
        ConstruirBotones()
    End Sub

    Public Sub ValidaAgregarItem()
        Dim tipoitem As Integer = ConexionSGS.EjecutarQueryScalar(String.Format("select idtipo from iditemventa "))
    End Sub

End Class